/**
 * 分类模块数据操作文件
 */

const { Op } = require('sequelize');
const { sequelize } = require('./common');
const { classify } = sequelize.models;

/**
 * 添加
 * @param {*} model 
 * @returns 
 */
const add = model => classify.create(model);

/**
 * 修改
 * @param {*} model 
 * @returns 
 */
const update = model => classify.update(model, { where: { id: model.id } });

/**
 * 删除
 * @param {*} id 
 * @returns 
 */
const deleteClass = id => classify.destroy({ where: { id } });

/**
 * 获取所有
 * @param {*} user_id 
 * @returns 
 */
const getAll = () => classify.findAll({ order: ['sort'] });

/**
 * 
 * @param {*} name 
 * @returns 
 */
const exists = (name, id = 0) => classify.findOne({
    where: {
        name,
        [Op.not]: {
            id
        }
    }, attributes: ['id']
});

/**
 * 是否还存在子分类
 * @param {*} pid 
 * @returns 
 */
const existChildren = pid => classify.findOne({
    where: {
        pid
    },
    attributes: ['id']
})

module.exports = {
    add,
    update,
    getAll,
    exists,
    deleteClass,
    existChildren
}